<style>

</style>
<template>
  <div>
    <el-table :data="userTable" :header-cell-style="{'text-align':'center'}" ref="table"
              :cell-style="{'text-align':'center'}">
      <el-table-column prop="id" label="id" width="100"/>
      <el-table-column prop="username" label="用户名" width="100"/>
      <el-table-column prop="nickname" label="用户昵称" width="100"/>
      <el-table-column prop="phone" label="用户手机号码" width="125"/>
      <el-table-column prop="email" label="用户邮箱" width="150"/>
      <el-table-column label="用户头像" width="100">
        <el-image style="width: 75px;height: 75px;overflow: hidden;border-radius: 50%" slot-scope="scope"
                  :src="scope.row.icon" fit="fill"/>
      </el-table-column>
      <el-table-column prop="isEnable" label="启用情况" width="150">
        <el-switch slot-scope="scope" v-model="scope.row.isEnable"
                   @change="isEnableSwitchUpdate(scope.row.id,scope.row.isEnable,scope.row.nickname)"
                   :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用"/>
      </el-table-column>
      <el-table-column prop="sort" label="用户序号" width="100"/>
      <el-table-column prop="created" label="创建时间" width="100"/>
      <el-table-column prop="updated" label="更新时间" width="100"/>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" circle icon="el-icon-search" @click="dataDrawerOpen(scope.row)"/>
          <el-button type="success" circle icon="el-icon-user-solid" @click="secretDrawerOpen(scope.row)"/>
          <el-popover width="250" placement="right" :ref="'deleteBy'+scope.row.id">
            <p style="text-align: center">确认删除：{{ scope.row.username }}？</p>
            <p style="text-align: center">(将滑动条移至右侧以解锁“确认”)</p>
            <el-slider style="width: 100px;margin: 0 auto" v-model="deleteLine" @change="deletePopoverMaxLine($event)"
                       :show-tooltip="false"/>
            <div style="text-align: center">
              <el-button :disabled="confirmDelete" type="danger" @click="deletePopoverUpdate(scope.row.id)">确认删除
              </el-button>
            </div>
            <el-button style="margin-left: 10px" circle slot="reference" type="danger" icon="el-icon-delete"
                       @click="deletePopoverOpen"/>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="page" :page-sizes="[5,10,20,30,40,50]" :page-size="pageSize"
                   layout="total, sizes, prev, pager, next, jumper" :total="total"/>

    <el-drawer :visible.sync="dataDrawer" :title="'正在修改：'+dataEditForm.name" ref="update">
      <el-form :model="dataEditForm" :rules="dataEditRule" style="max-width: 450px" ref="updateForm" label-width="120px">
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="dataEditForm.nickname" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="用户头像" prop="icon">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9999/zx-resource/resources/upload/image/product"
              :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="handleAvatarChange">
            <img v-if="dataEditForm.icon" :src="dataEditForm.icon" class="avatar" alt="404">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户手机号码" prop="phone">
          <el-input v-model="dataEditForm.phone" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="dataEditForm.email" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="启用情况">
          <el-switch slot-scope="scope" v-model="dataEditForm.isEnable"
                     :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用"/>
        </el-form-item>
        <el-form-item label="序号" prop="sort">
          <el-input v-model="dataEditForm.sort" autocomplete="off"/>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" style="margin-right: 150px" @click="dataDrawerUpdate">修改</el-button>
          <el-button type="danger" @click="dataDrawerClose">取消</el-button>
        </div>
      </el-form>
    </el-drawer><!--普通数据修改栏-->

    <el-drawer :visible.sync="secretDrawer" :title="'正在修改账户：'+secretEditForm.username" ref="updateSecret">
      <el-form :model="secretEditForm" :rules="secretRules" style="width: 500px">
        <el-form-item label="账号" prop="username" label-width="100px">
          <el-input v-model="secretEditForm.username" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="100px">
          <el-input v-model="secretEditForm.password" autocomplete="off"/>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" style="margin-right: 150px" @click="secretDrawerUpdate()">修改</el-button>
          <el-button type="danger" @click="secretDrawerClose">取消</el-button>
        </div>
      </el-form>
    </el-drawer><!--隐私数据修改栏-->
  </div>
</template>

<script>
export default {
  name: "usersList",
  data() {
    return {
      secretDrawer: false,
      confirmDelete: true,
      deleteLine: 0,
      dataDrawer: false,
      page: parseInt(""),//当前页数
      pageSize: parseInt(""),//每页展示数
      total: parseInt(""),//最大数据量
      totalPage: parseInt(""),//最大页码
      userTable: [],
      dataEditForm: {
        id: "",
        nickname: "",
        phone: "",
        email: "",
        icon: "",
        isEnable: "",
        sort: ""
      },
      dataEditRule: {
        id: [],
        nickname: [
          {required: true, message: "请输入用户昵称", trigger: "blur"},
          {min: 1, max: 15, message: "昵称长度需在1~15个字符之间", trigger: "blur"}
        ],
        phone: [
          {required: true, message: "请输入用户手机号码", trigger: "blur"},
        ],
        email: [],
        icon: [],
        isEnable: [],
        sort: []
      },
      secretEditForm: {
        id: "",
        username: "",
        password: "",
      },
      secretRules: {
        username: [
          {required: true, message: "请输入新的账户名", trigger: "blur"},
          {max: 15, message: "账户名长度需在1~15个字符之间", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入新的密码", trigger: "blur"},
        ]
      },
    }
  },
  methods: {
    //图片
    handleAvatarChange() {
      let data = this.qs.stringify({"imageUrl": this.dataEditForm.icon})
      let url = "http://localhost:9999/zx-resource/resources/deleteImg"
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, data)
    },
    handleAvatarSuccess(response) {
      this.dataEditForm.icon = response.data.url
    },

    dataDrawerUpdate() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          let url = "http://localhost:9999/zx-ums/user/updateData";
          let formData = this.qs.stringify(this.dataEditForm);
          this.axios.create(
              {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
          ).post(url, formData).then((response) => {
            if (response.data.state === 200) {
              this.$message({message: "数据已修改，正在刷新页面", type: "success"});
              this.loadUser();
            } else {
              this.$message({message: response.data.message, type: "error"})
            }
          })
          this.dataDrawerClose();
        } else {
          this.$message({message: "数据尚未符合要求", type: "error"})
        }
      })
    },//确认修改窗口内容并触发closingDrawer
    secretDrawerUpdate() {
      let formData = this.qs.stringify(this.secretEditForm);
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post("http://localhost:9999/zx-ums/user/updateAccount", formData).then((response) => {
        if (response.data.state === 200) {
          this.$message({message: "完成修改，自动刷新页面以获取最新内容", type: "success"})
          this.loadUser();
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
      this.secretDrawerClose()
    },//提交新隐私数据，同时关闭隐私数据修改侧边栏
    secretDrawerClose() {
      this.secretDrawer = false;
    },//用于关闭隐私数据修改侧边栏
    dataDrawerClose() {
      this.dataDrawer = false;
    },//关闭修改侧边栏
    deletePopoverOpen() {
      this.deleteLine = 0;
      this.confirmDelete = true;
    },//打开Popover组件，delete
    deletePopoverUpdate(id) {
      let url = "http://localhost:9999/zx-ums/user/deleteById";
      let fromData = this.qs.stringify({"id": id});
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, fromData).then((response) => {
        if (response.data.state === 200) {
          this.$message({message: "删除完毕，正在刷新页面", type: "success"});
          this.loadUser();
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
      this.$refs[`deleteBy` + id].doClose();
    },//根据id执行删除并关闭对应的popover删除窗口
    deletePopoverMaxLine(index) {
      if (index !== 100) {
        this.deleteLine = 0;
      }
      this.confirmDelete = index !== 100;
    },//检查删除确认条是否拉到右侧
    secretDrawerOpen(data) {
      this.secretEditForm.id = data.id;
      this.secretEditForm.username = data.username;
      this.secretEditForm.password = data.password;
      this.secretDrawer = true;
    },//打开隐私数据修改侧边栏，同时获取对应的数据
    dataDrawerOpen(data) {
      let url = "http://localhost:9999/zx-ums/user/standard?id=" + data.id
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          jsonResult = jsonResult.data;
          this.dataEditForm = jsonResult;
          this.dataEditForm.name = jsonResult.nickname;
          this.dataDrawer = true
        } else {
          this.$message({message: "获取数据失败，调用本地数据"})
          this.dataEditForm = data;
        }
      })

    },//打开修改侧边栏
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.loadUser();
    },//切换每页数量
    handleCurrentChange(pageNum) {
      this.page = pageNum;
      this.loadUser();
    },//切换页码
    isEnableSwitchUpdate(id, is_enable, nickname) {
      let url = "http://localhost:9999/zx-ums/user/updateIsEnable";
      let formData = this.qs.stringify({"id": id, "isEnable": is_enable});
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, formData).then((response) => {
        if (response.data.state === 200) {
          if (is_enable === 1) {
            this.$message({message: "已启用" + nickname, type: "success"})
          } else {
            this.$message({message: "已禁用" + nickname, type: "warning"})
          }
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
    },//变更is_enable字段
    loadUser() {
      if (isNaN(this.page)) this.page = 1;
      if (isNaN(this.pageSize)) this.pageSize = 5;
      let url = "http://localhost:9999/zx-ums/user/list?page=" + this.page + "&pageSize=" + this.pageSize
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        if (response.data.state === 200) {
          this.userTable = response.data.data.list
          this.pageSize = response.data.data.pageSize;
          this.total = response.data.data.total;
          this.totalPage = response.data.data.totalPage;
        }
      })
    }
  },
  mounted() {
    this.loadUser();
    this.$message({
      message: "警告：用户信息为用户在本站的虚拟财产，未经用户允许，严禁修改、删除",
      type: "warning",
      duration: 5000
    })
  }
}
</script>